/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.proof;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.utils.DataUtils;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.photo.ThumbnailControl;
import cn.ac.nercis.pes.community.constant.SaveMethod;
import cn.ac.nercis.pes.community.constant.ThumbnailSize;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.controller.evaluation.prepare.course.EvalProcessFastController;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.prepare.course.EvalProcessFastView;
import cn.ac.nercis.pes.community.views.evaluation.proof.ProofView;
import cn.ac.nercis.pes.model.dto.evaluation.content.proof.ActivityDTO;
import cn.ac.nercis.pes.model.dto.evaluation.prepare.EvaluationStageDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationProcessService;
import cn.ac.nercis.pes.service.evaluation.ProofService;
import cn.ac.nercis.pes.service.utils.FileManage;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 密评活动证明管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class ActivityController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    private final static String TRAVEL_NAME = "差旅票证";
    private final static String STAY_NAME = "住宿账单";
    private final static String STAY_INVOICE_NAME = "住宿费发票";
    private final static String SIGN_FORM_NAME = "现场测评签到表";
    private final static String SCENE_PHOTO_NAME = "现场照片";
    private final static String DOCKING_NAME = "对接记录";
    private final static String IN_OUT_NAME = "机房出入记录";
    @FXML
    private StackPane page;
    @FXML
    private Button planButton;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private ListView<MenuVO> menuList;
    @FXML
    private VBox ticketBox;
    @FXML
    private VBox recordBox;
    @FXML
    private DatePicker startDateTicketPicker;
    @FXML
    private DatePicker endDateTicketPicker;
    @FXML
    private TextField unitTicketTxt;
    @FXML
    private TextField personTicketTxt;
    @FXML
    private VBox travelFileTicketPictureBox;
    @FXML
    private Button addTravelFileTicketPictureBtn;
    @FXML
    private VBox stayFileTicketPictureBox;
    @FXML
    private Button addStayFileTicketPictureBtn;
    @FXML
    private VBox stayInvoiceFileTicketPictureBox;
    @FXML
    private Button addStayInvoiceFileTicketPictureBtn;

    @FXML
    private DatePicker startDateRecordPicker;
    @FXML
    private DatePicker endDateRecordPicker;
    @FXML
    private TextField unitRecordTxt;
    @FXML
    private TextField addressRecordTxt;
    @FXML
    private VBox signFormFileRecordPictureBox;
    @FXML
    private Button addSignFormFileRecordPictureBtn;
    @FXML
    private VBox scenePhotoFileRecordPictureBox;
    @FXML
    private Button addScenePhotoFileRecordPictureBtn;
    @FXML
    private VBox dockingFileRecordPictureBox;
    @FXML
    private Button addDockingFileRecordPictureBtn;
    @FXML
    private VBox inOutFileRecordPictureBox;
    @FXML
    private Button addInOutFileRecordPictureBtn;

    private final ProofService proofService;
    private final EvaluationProcessService processService;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);
    private String currentSystemId;

    public ActivityController() {
        this.proofService = SpringUtils.getBean(ProofService.class);
        this.processService = SpringUtils.getBean(EvaluationProcessService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        planButton.setGraphic(IconUtils.getGlyph("check-icon","btn-icon"));
        addTravelFileTicketPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addStayFileTicketPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addStayInvoiceFileTicketPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addSignFormFileRecordPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addScenePhotoFileRecordPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addDockingFileRecordPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addInOutFileRecordPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));

        this.initializeMenu();
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerDateChange(startDateTicketPicker,endDateTicketPicker,startDateRecordPicker,endDateRecordPicker);
        realTimeSaveManager.listenerTextChange(personTicketTxt,addressRecordTxt);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化密评活动证明信息...");
        this.currentSystemId = systemId;
        this.menuList.getSelectionModel().select(0);
        loadActivity();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        saveActivity(SaveMethod.SAVE, false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        saveActivity(SaveMethod.SAVE, false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        saveActivity(SaveMethod.SAVE, true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        saveActivity(SaveMethod.SAVE_NOW,false);
    }

    @FXML
    private void onAddTravelFileTicketPictureClick(){
        addPictureClick(this.travelFileTicketPictureBox,addTravelFileTicketPictureBtn,TRAVEL_NAME);
    }

    @FXML
    private void onAddStayFileTicketPictureClick(){
        addPictureClick(this.stayFileTicketPictureBox,addStayFileTicketPictureBtn,STAY_NAME);
    }

    @FXML
    private void onAddStayInvoiceFileTicketPictureClick(){
        addPictureClick(this.stayInvoiceFileTicketPictureBox,addStayInvoiceFileTicketPictureBtn,STAY_INVOICE_NAME);
    }

    @FXML
    private void onAddSignFormFileRecordPictureClick(){
        addPictureClick(this.signFormFileRecordPictureBox,addSignFormFileRecordPictureBtn,SIGN_FORM_NAME);
    }

    @FXML
    private void onAddScenePhotoFileRecordPictureClick(){
        addPictureClick(this.scenePhotoFileRecordPictureBox,addScenePhotoFileRecordPictureBtn,SCENE_PHOTO_NAME);
    }

    @FXML
    private void onAddDockingFileRecordPictureClick(){
        addPictureClick(this.dockingFileRecordPictureBox,addDockingFileRecordPictureBtn,DOCKING_NAME);
    }

    @FXML
    private void onAddInOutFileRecordPictureClick(){
        addPictureClick(this.inOutFileRecordPictureBox,addInOutFileRecordPictureBtn,IN_OUT_NAME);
    }

    @FXML
    private void onShowPlan(){
        LogUtils.info(log, "查看测评计划操作...");
        var showView = AppStore.getEvaluationView(this.currentSystemId, EvalProcessFastView.class);
        PageDialog dialog = PageDialog.builder()
                .withIcon("check-icon")
                .withTitle("查看测评计划")
                .withContent(Objects.requireNonNull(showView).load())
                .withOverlayClose(false)
                .withShowActions(false)
                .withOwner(AppStore.getCurrentSystem(this.currentSystemId).getEvaluationStage())
                .build();
        if(showView.getController() instanceof EvalProcessFastController controller){
            controller.initializeData(this.currentSystemId);
        }
        dialog.show();
    }

    private void initializeMenu(){
        this.menuList.setCellFactory(cf->new MenuListCell());
        this.menuList.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if(Objects.nonNull(newValue)){
                        loadContent(newValue);
                    }
                });
        this.menuList.getItems().add(new MenuVO(1,"ticket","旅住宿等票证",""));
        this.menuList.getItems().add(new MenuVO(2,"record","进场记录",""));
    }

    private void loadContent(MenuVO menu){
        if(StringUtils.equals(menu.getCode(),"ticket")){
            this.recordBox.setVisible(false);
            this.ticketBox.setVisible(true);
        } else {
            this.ticketBox.setVisible(false);
            this.recordBox.setVisible(true);
        }
    }

    private void loadActivity() {
        LogUtils.info(log, "获取密评活动证明信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        //清空页面旧的图片
        CompletableFuture.supplyAsync(() -> this.proofService.findActivity(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    initTicket(res);
                    initRecord(res);
                }))
                .exceptionally((ex) -> {
                    log.error("获取密评活动证明信息出错!", ex);
                    return null;
                });
    }

    private void initTicket(ActivityDTO activityDTO){
        startDateTicketPicker.setValue(activityDTO.getStartDateTicket());
        endDateTicketPicker.setValue(activityDTO.getEndDateTicket());
        unitTicketTxt.setText(activityDTO.getUnitTicket());
        personTicketTxt.setText(activityDTO.getPersonTicket());
        loadThumbnailPicture(activityDTO.getTravelFileTicket(),travelFileTicketPictureBox,addTravelFileTicketPictureBtn,TRAVEL_NAME);
        loadThumbnailPicture(activityDTO.getStayFileTicket(),stayFileTicketPictureBox,addStayFileTicketPictureBtn,STAY_NAME);
        loadThumbnailPicture(activityDTO.getStayInvoiceFileTicket(),stayInvoiceFileTicketPictureBox,addStayInvoiceFileTicketPictureBtn,STAY_INVOICE_NAME);
    }

    private void initRecord(ActivityDTO activityDTO){
        startDateRecordPicker.setValue(activityDTO.getStartDateRecord());
        endDateRecordPicker.setValue(activityDTO.getEndDateRecord());
        unitRecordTxt.setText(activityDTO.getUnitRecord());
        addressRecordTxt.setText(activityDTO.getAddressRecord());
        loadThumbnailPicture(activityDTO.getSignFormFileRecord(),signFormFileRecordPictureBox,addSignFormFileRecordPictureBtn,SIGN_FORM_NAME);
        loadThumbnailPicture(activityDTO.getScenePhotoFileRecord(),scenePhotoFileRecordPictureBox,addScenePhotoFileRecordPictureBtn,SCENE_PHOTO_NAME);
        loadThumbnailPicture(activityDTO.getDockingFileRecord(),dockingFileRecordPictureBox,addDockingFileRecordPictureBtn,DOCKING_NAME);
        loadThumbnailPicture(activityDTO.getInOutFileRecord(),inOutFileRecordPictureBox,addInOutFileRecordPictureBtn,IN_OUT_NAME);
    }

    private void saveActivity(SaveMethod saveMethod, boolean finish) {
        if (finish && !this.validContent()) {
            return;
        }
        var activity = ActivityDTO.builder()
                .startDateTicket(startDateTicketPicker.getValue())
                .endDateTicket(endDateTicketPicker.getValue())
                .unitTicket(this.unitTicketTxt.getText())
                .personTicket(this.personTicketTxt.getText())
                .travelFileTicket(getPicture(this.travelFileTicketPictureBox))
                .stayFileTicket(getPicture(this.stayFileTicketPictureBox))
                .stayInvoiceFileTicket(getPicture(this.stayInvoiceFileTicketPictureBox))
                .startDateRecord(this.startDateRecordPicker.getValue())
                .endDateRecord(this.endDateRecordPicker.getValue())
                .unitRecord(this.unitRecordTxt.getText())
                .addressRecord(this.addressRecordTxt.getText())
                .signFormFileRecord(getPicture(this.signFormFileRecordPictureBox))
                .scenePhotoFileRecord(getPicture(this.scenePhotoFileRecordPictureBox))
                .dockingFileRecord(getPicture(this.dockingFileRecordPictureBox))
                .inOutFileRecord(getPicture(this.inOutFileRecordPictureBox))
                .build();
        LogUtils.info(log, "保存密评活动证明信息...");
        LogUtils.record(log, "请求数据：systemId:{},data:{}", this.currentSystemId, activity);
        CompletableFuture.supplyAsync(() -> this.proofService.saveActivity(this.currentSystemId, activity))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishProcess(finish);
                        if (saveMethod == SaveMethod.SAVE) {
                            AppUtils.showMessageDialog("保存成功", MessageType.SUCCESS,this.page);
                        }
                    } else {
                        if(saveMethod == SaveMethod.SAVE_NOW){
                            log.error("即时保存失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存密评活动证明信息出错!", ex);
                    return null;
                });
    }

    public boolean validContent() {
        var stage = this.processService.getEvaluationStage(this.currentSystemId);
        if (Objects.isNull(stage)) {
            return true;
        }
        if (!validDateRange(startDateTicketPicker, endDateTicketPicker, stage, "旅住宿等票证")) {
            return false;
        }
        return validDateRange(startDateRecordPicker, endDateRecordPicker, stage, "进场记录");
    }

    private boolean validDateRange(DatePicker start, DatePicker end, EvaluationStageDTO stage, String name){
        var evalStartDate = stage.getEvaluationStartDate();
        var evalEndDate = stage.getEvaluationEndDate();
        if(Objects.isNull(evalStartDate) || Objects.isNull(evalEndDate)){
            return true;
        }
        long between =  DataUtils.between(start.getValue(),end.getValue(), ChronoUnit.DAYS);
        if(between < 1){
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN)
                    .withMessage(String.format("%s，离场时间必须大于入场时间",name))
                    .build().show();
            return false;
        }
        if(!DataUtils.range(start.getValue(),evalStartDate,evalEndDate)){
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN)
                    .withMessage(String.format("%s，入场时间必须在测评实施过程时间范围内！",name))
                    .build().show();
            return false;
        }
        if(!DataUtils.range(end.getValue(),evalStartDate,evalEndDate)){
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN)
                    .withMessage(String.format("%s，离场时间必须在测评实施过程时间范围内！",name))
                    .build().show();
            return false;
        }
        return true;
    }

    private void loadThumbnailPicture(String pictureName,VBox pictureBox,Button addBtn,String name){
        if(StringUtils.isBlank(pictureName)){
            return;
        }
        File pictureFile = FileUtils.getFile(FileManage.getActivityDir(this.currentSystemId),pictureName);
        if(!pictureFile.exists()){
            return;
        }
        try {
            ThumbnailControl thumbnailControl = new ThumbnailControl(pictureFile,this.page, ThumbnailSize.NORMAL_X2);
            thumbnailControl.setOnRenameEvent(this::onRenameFileChick);
            if(StringUtils.equals(name,TRAVEL_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.travelFileTicketPictureBox,this.addTravelFileTicketPictureBtn,TRAVEL_NAME));
            }else if(StringUtils.equals(name,STAY_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.stayFileTicketPictureBox,this.addStayFileTicketPictureBtn,STAY_NAME));
            }else if(StringUtils.equals(name,STAY_INVOICE_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.stayInvoiceFileTicketPictureBox,this.addStayInvoiceFileTicketPictureBtn,STAY_INVOICE_NAME));
            }else if(StringUtils.equals(name,SIGN_FORM_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.signFormFileRecordPictureBox,this.addSignFormFileRecordPictureBtn,SIGN_FORM_NAME));
            }else if(StringUtils.equals(name,SCENE_PHOTO_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.scenePhotoFileRecordPictureBox,this.addScenePhotoFileRecordPictureBtn,SCENE_PHOTO_NAME));
            }else if(StringUtils.equals(name,DOCKING_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.dockingFileRecordPictureBox,this.addDockingFileRecordPictureBtn,DOCKING_NAME));
            }else{
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.inOutFileRecordPictureBox,this.addInOutFileRecordPictureBtn,IN_OUT_NAME));
            }
            pictureBox.getChildren().add(thumbnailControl);
            //隐藏添加图片按钮
            addBtn.setVisible(false);
        } catch (IOException ex) {
            log.error(String.format("加载%s图片文件失败：",name), ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage(String.format("载入%s图片文件失败",name))
                    .build().show();
        }
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, ProofView.class);
        if(prepareView.getController() instanceof ProofController controller){
            controller.setEvalProcess(EvaluationModule.PROOF_ACTIVITY, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }

    private String getPicture(VBox pictureBox){
        return pictureBox.getChildren()
                .stream()
                .filter(n->n instanceof ThumbnailControl)
                .map(n->(ThumbnailControl)n)
                .map(ThumbnailControl::getPictureFile)
                .map(File::getName)
                .findFirst()
                .orElse("");
    }

    private void addPictureClick(VBox pictureBox,Button addBtn,String name){
        LogUtils.info(log, String.format("执行%s添加图片操作...",name));
        if(pictureBox.getChildren().size()>0){
            AlertDialog alertDialog = AlertDialog.builder()
                    .withMode(AlertMode.CONFIRM)
                    .withType(AlertType.WARN)
                    .withTitle("操作提示")
                    .withContent(String.format("当前已存在%s，继续操作将进行覆盖！",name))
                    .withContainer(this.page)
                    .build();
            alertDialog.show((confirm)->{
                if(!confirm){
                    return;
                }
                addPicture(pictureBox,addBtn,name);
            });
        }else{
            addPicture(pictureBox,addBtn,name);
        }
    }

    private void addPicture(VBox pictureBox,Button addBtn,String name){
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle(String.format("选%s图片文件",name));
        fileChooser.getExtensionFilters().addAll(ControlUtils.getImageExtensionFilters());
        var currentSystem = AppStore.getCurrentSystem(this.currentSystemId);
        File selectFile = fileChooser.showOpenDialog(Objects.requireNonNull(currentSystem).getEvaluationStage());
        if(Objects.isNull(selectFile)){
            return;
        }
        try {
            File pictureFile = storePictureFile(selectFile);
            loadThumbnailPicture(pictureFile.getName(),pictureBox,addBtn,name);
            saveActivity(SaveMethod.SAVE_NOW,false);
        }catch (IOException ex){
            log.error(String.format("添加%s图片文件出错：",name),ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN)
                    .withMessage(String.format("添加%s图片文件失败！",name))
                    .build().show();
        }
    }

    protected void onRenameFileChick(ThumbnailControl source, String oldValue, String newValue) {
        LogUtils.info(log, "执行图片文件重命名操作...");
        if (StringUtils.isBlank(newValue)) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("图片文件名不能为空！")
                    .build().show();
            return;
        }
        if (StringUtils.equals(oldValue, newValue)) {
            source.setEditMode(false);
            return;
        }
        String newFileName = newValue.concat(FileManage.getFileSuffix(source.getPictureFile().getName()));
        boolean result = source.renamePhotoFile(newFileName);
        if (!result) {
            source.renamePhotoFile(oldValue);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL)
                    .withMessage("图片文件重命名失败！")
                    .build().show();
            return;
        }
        source.setEditMode(false);
        saveActivity(SaveMethod.SAVE_NOW, false);
    }

    private void onDeleteClick(ThumbnailControl source,VBox pictureBox,Button addBtn,String name){
        LogUtils.info(log, String.format("执行%s图片文件删除操作...",name));
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent(String.format("是否删除当前%s图片文件？",name))
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            pictureBox.getChildren().remove(source);
            removeStoreFile(source.getPictureFile());
            saveActivity(SaveMethod.SAVE_NOW,false);
            //显示添加图片按钮
            addBtn.setVisible(true);
        });
    }

    private void removeStoreFile(@NonNull File file){
        try {
            FileUtils.delete(file);
        }catch (IOException ex){
            log.error(String.format("删除%s图文件失败：",file.getName()),ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("移除图文件失败")
                    .build().show();
        }
    }

    private File storePictureFile(@NonNull File file) throws IOException {
        File saveFile = FileUtils.getFile(FileManage.getActivityDir(this.currentSystemId),file.getName());
        FileManage.copyFile(file,saveFile);
        return saveFile;
    }

}